package io.renren.modules.webapi.controller;

import cn.hutool.json.JSONObject;
import io.renren.common.utils.HttpClientUtils;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/webapi/wx")
public class WxController {

    @Value("${wx.accountId}")
    private String accountId;

    @Value("${wx.accountSecret}")
    private String accountSecret;

    @RequestMapping("/getOpenId")
    public R getOpenId(@RequestParam("code") String code) {
        String result = "";
        try{
            //请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                    + this.accountId + "&secret="
                    + this.accountSecret + "&js_code="
                    + code
                    + "&grant_type=authorization_code";
            result = HttpClientUtils.doGet(url);
            JSONObject json = new JSONObject(result);
            return R.ok().put("openId",result);
        }
        catch (Exception e) {
            return R.error();
        }
    }
}
